package com.ctshk.rpc.order.ship.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.CurrencyRateExchangeConstant;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.common.utils.*;
import com.ctshk.rpc.booking.enums.SupplierReserveTypeEnum;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierOrderSystemShipAddReq;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierSystemOrderShipAddReq;
import com.ctshk.rpc.booking.req.system.ship.add.SupplierSystemOrderShipTicketAddReq;
import com.ctshk.rpc.booking.service.ISupplierOrderService;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.req.bill.BillAddCollectionReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.insurance.service.IInsuranceService;
import com.ctshk.rpc.iotc.dto.OperateBankPreferenceQueryDTO;
import com.ctshk.rpc.iotc.req.OperateBankConformQueryReq;
import com.ctshk.rpc.iotc.service.IOperateBankPreferenceService;
import com.ctshk.rpc.order.ship.dto.*;
import com.ctshk.rpc.order.ship.dto.ShipConstants;
import com.ctshk.rpc.order.ship.dto.ShipReserveDTO;
import com.ctshk.rpc.order.ship.dto.cport.AppShipOrderAmountItem;
import com.ctshk.rpc.order.ship.dto.cport.AppShipOrderInfoDTO;
import com.ctshk.rpc.order.ship.entity.*;
import com.ctshk.rpc.order.ship.enums.ShipCompanyEnums;
import com.ctshk.rpc.order.ship.generator.ShipOrderGenerator;
import com.ctshk.rpc.order.ship.mapper.*;
import com.ctshk.rpc.order.ship.req.*;
import com.ctshk.rpc.order.ship.service.IAppShipOrderService;
import com.ctshk.rpc.order.ship.service.IShipOrderReceiptService;
import com.ctshk.rpc.ship.dto.*;
import com.ctshk.rpc.ship.dto.ShipReserveListDTO;
import com.ctshk.rpc.ship.req.*;
import com.ctshk.rpc.ship.req.app.AppShipProductIsRecommendedReq;
import com.ctshk.rpc.ship.req.app.PeoplesPriceDto;
import com.ctshk.rpc.ship.service.IAppShipProductService;
import com.ctshk.rpc.ship.service.IShipProductSaleRecordService;
import com.ctshk.rpc.system.dto.MainDataCurrencyListDTO;
import com.ctshk.rpc.system.dto.MainDataCurrencyQueryDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.DispatchOrderRuleGetUserReq;
import com.ctshk.rpc.system.req.MainDataCurrencyListReq;
import com.ctshk.rpc.system.service.IDispatchOrderRuleService;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.github.houbb.heaven.util.lang.StringUtil;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author wansi <gaylen15527491065@yeah.net>
 * @Date 2021/5/28
 */
@Slf4j
@DubboService
public class AppShipOrderServiceImpl extends ServiceImpl<ShipOrderMapper,ShipOrder> implements IAppShipOrderService {

    @DubboReference
    private IAppShipProductService iAppShipProductService;
    @Autowired
    private ShipOrderTouristMapper shipOrderTouristMapper;
    @Autowired
    private ShipOrderRouteMapper shipOrderRouteMapper;
    @Autowired
    private ShipOrderMapper shipOrderMapper;
    @DubboReference
    private IShipProductSaleRecordService iShipProductSaleRecordService;
    @DubboReference
    private ISysUserService iSysUserService;
    @Autowired
    private ShipOrderInsuranceMapper shipOrderInsuranceMapper;
    @DubboReference
    private IInsuranceService iInsuranceService;
    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;
    @DubboReference
    private IShipOrderReceiptService iShipOrderReceiptService;
    @DubboReference
    private IFinanceBillService iFinanceBillService;
    @DubboReference
    private IOperateBankPreferenceService operateBankPreferenceService;
    @Autowired
    private ShipOrderCollectionMapper shipOrderCollectionMapper;
    @DubboReference
    private ISupplierOrderService iSupplierOrderService;
    @Autowired
    private ShipOrderRefundMapper shipOrderRefundMapper;
    @DubboReference
    private ISysApprovalService iSysApprovalService;
    @DubboReference
    private IDispatchOrderRuleService iDispatchOrderRuleService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveShipOrder(AppShipOrderReq shipOrderReq) {
        log.info("[C-船票下单操作]");
        /**---------------------------------------------定义订单信息 开始-------------------------------------------------**/
        AppShipOrderAmountItem shipOrderAmountItem = new AppShipOrderAmountItem();
        //成人总票数
        AtomicInteger adultTotalNumber = new AtomicInteger(0);
        //小童总票数
        AtomicInteger childrenTotalNumber = new AtomicInteger(0);
        //订单保存的产品ID用逗号间隔
        StringBuffer productIds = new StringBuffer();
        //是否单程或者往返 , 默认单程
        AtomicInteger tripTypeFlag = new AtomicInteger(0);
        //总orderDetail
        List<ShipOrderDetailListDTO> shipAllOrderDetailList = Lists.newArrayListWithExpectedSize(5);
        //同一个订单，仅插入一次旅客信息
        AtomicBoolean touristSwitch = new AtomicBoolean(true);
        //旅客Id映射关系
        Map<Long, ShipOrderTourist> touristMap = Maps.newHashMap();
        //去程、返程 旅客船票價格映射
        Map<Long,Map<Integer, BigDecimal>> priceMap = Maps.newHashMap();
        //去程、返程 旅客稅費映射
        Map<Long,BigDecimal> taxMap = Maps.newHashMap();
        /**----------------------------------------------定义订单信息 结束------------------------------------------------**/

        //1.订单ID  保存订单相关信息
        Long orderId = SnowflakeIdWorker.nextId();
        for (ShipOrderRouteProductReq shipOrderRouteProductReq : shipOrderReq.getShipOrderRouteProductList()) {
            AppShipProductIsRecommendedReq shipProductIsRecommendedReq = queryShipInfo(shipOrderRouteProductReq,shipOrderRouteProductReq);
            shipProductIsRecommendedReq.setId(Long.valueOf(shipOrderRouteProductReq.getProductId()));
            List<ShipReserveListDTO> shipReserveListDTOS = iAppShipProductService.queryReserveList(shipProductIsRecommendedReq,shipOrderReq.getChannelId(),shipOrderRouteProductReq.getProductId());
            if (CollectionUtils.isEmpty(shipReserveListDTOS)) {
                return Result.failed(SystemError.SHIP_PRODUCT_11024);
            }
            //<1>.获取航线的产品信息
            ShipReserveListDTO shipReserveListDTO = shipReserveListDTOS.get(0);

            //<2>.保存订单的旅行信息
            ShipReserveDTO shipReserveDTO = saveOrderTouristInfo(shipOrderRouteProductReq.getProductId(), null, touristMap, shipOrderAmountItem, adultTotalNumber, childrenTotalNumber, orderId, shipOrderReq.getShipOrderTouristList(), touristSwitch.get(), shipReserveListDTO,shipOrderRouteProductReq.getStartDate(),priceMap,shipOrderReq.getChannelId());

            //<3>.保存订单的航线信息  往返票/单程票-航线信息
            saveShipOrderRoute(shipOrderAmountItem.getAdultAmount(), shipOrderAmountItem.getChildrenAmount(),
                    shipOrderAmountItem.getAdultTaxAmount(), shipOrderAmountItem.getChildrenTaxAmount(), orderId, shipAllOrderDetailList, shipOrderRouteProductReq, shipReserveListDTO, shipOrderAmountItem.getAdultNumber(), shipOrderAmountItem.getChildrenNumber(), shipReserveDTO);

            //<4>.减产品库存
            saveSaleRecord(orderId, shipOrderRouteProductReq, shipReserveListDTO.getId(),shipOrderReq.getChannelId());

            //<5>.其他
            //拼接产品信息
            productIds.append(shipReserveDTO.getId() + ",");
            shipOrderAmountItem.getDepCity().append(shipReserveListDTO.getDepCityName() + "/");
            shipOrderAmountItem.getArrCity().append(shipReserveListDTO.getArrCityName() + "/");
            shipOrderAmountItem.getDepPlace().append(shipReserveListDTO.getDepPlaceName() + "/");
            shipOrderAmountItem.getArrPlace().append(shipReserveListDTO.getArrPlaceName() + "/");
            shipOrderAmountItem.getVoyage().append(shipReserveListDTO.getVoyage() + "/");
            shipOrderAmountItem.getCompanyType().append(ShipCompanyEnums.getCompanyName(shipReserveListDTO.getCompanyType()) +"/");
            shipOrderAmountItem.setCabinClassName(StringUtils.isEmpty(shipReserveListDTO.getCabinClassName())?
                    shipReserveListDTO.getCabinClassStr():shipReserveListDTO.getCabinClassName());
            //服务费 = 預定服務費+稅費
            shipOrderAmountItem.setServiceAmount(shipOrderAmountItem.getServiceAmount()
                    .add(shipReserveDTO.getServicePrice()
                            .add(shipReserveDTO.getTaxPrice())));
            taxMap.put(shipReserveListDTO.getId(),shipReserveDTO.getServicePrice().add(shipReserveDTO.getTaxPrice()));
            touristSwitch.set(false);
            tripTypeFlag.incrementAndGet();
        }

        //新增旅客信息表價格信息
        updateTouristPrice(priceMap,taxMap,orderId);

        //产品ID拼接串
        String ids = productIds.substring(0, productIds.length() - 1);

        //2.插入订单信息
        saveOrderInfo(shipOrderReq, shipOrderAmountItem, adultTotalNumber.get(),
                childrenTotalNumber.get(), orderId, ids, tripTypeFlag, shipAllOrderDetailList);
        log.info("[C-船票下单成功]");

        return Result.success(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result payOrder(AppShipOrderCollectionReq appShipOrderCollectionReq) {
        /**-----------------------------------------订单基础数据准备------------------------------------------*/
        log.info("回调船票后台收款接口----入参：{}",JSON.toJSONString(appShipOrderCollectionReq));

        Long id = appShipOrderCollectionReq.getId();
        ShipOrder shipOrder = shipOrderMapper.selectById(id);
        if(shipOrder == null){
            throw new BusinessException(SystemError.SHIP_PRODUCT_11032);
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        //获取用户信息
        UserDTO userDTO = getUserDTO();

        //资源信息列表
        List<String> resourceInfoList = Lists.newArrayList();
        //存放产品id列表
        List<Long> ids = Lists.newArrayList();
        Set<String> supplierSize = Sets.newHashSetWithExpectedSize(2);
        /**-----------------------------------------订单操作------------------------------------------*/
        //1.訂單校驗
        Result checkResult = checkOrderData(shipOrder,nowLocalDateTime,appShipOrderCollectionReq);
        if (checkResult != null) return checkResult;

        //2.收款記錄
        ShipOrderCollection shipOrderCollection = addOrderCollection(id, nowLocalDateTime, appShipOrderCollectionReq,userDTO);

        //3.供应商预订单接口
        String productIds = shipOrder.getProductId();
        Integer isConfirm = 1;
        if (!StringUtils.isEmpty(productIds)) {
            String[] idArray = productIds.split(",");
            for (String productId : idArray) {
                ShipProductDetailDTO shipProductDetailDTO = iAppShipProductService.queryDetail(Long.valueOf(productId));
                //产品供应商不同，分别下2个供应商预订单
                if(supplierSize.size() == 0 || !supplierSize.contains(shipProductDetailDTO.getSupplierId())){
                    isConfirm = shipProductDetailDTO.getIsConfirm();
                    extracted(shipOrder, shipProductDetailDTO,supplierSize,userDTO);
                }
                ids.add(Long.valueOf(productId));
                resourceInfoList.add(shipProductDetailDTO.getDepPlaceName() + "-" + shipProductDetailDTO.getArrPlaceName());
            }
        }

        //4.訂單收據
        //TODO
        TokenUser tokenUser = new TokenUser();
        tokenUser.setId(userDTO.getId());
        iShipOrderReceiptService.add(id, tokenUser);

        //5.更新訂單狀態
        shipOrder.setPaymentStatus(OrderPaymentStatus.ALREADY_PAYMENT.getCode());
        //立即确认，则下单后自行确认 (0 立即确认, 1 二次确认)
        if(isConfirm == 0){
            shipOrder.setScheduledStatus(OrderScheduledStatus.RESERVE_SUCCESS.getCode());
        }else {
            shipOrder.setScheduledStatus(OrderScheduledStatus.CONFIRM_RESERVE.getCode());
        }
        shipOrder.setModifiedId(userDTO.getId());
        shipOrder.setGmtModified(nowLocalDateTime);
        shipOrderMapper.updateById(shipOrder);

        //7.申請收款認款
        Result billResult = iFinanceBillService.addCollection(obtainBillCollection(id, shipOrder,shipOrderCollection,
                appShipOrderCollectionReq, resourceInfoList, ids));
        if (billResult.getCode() != 0){
            throw new BusinessException(SystemError.SHIP_PRODUCT_11042, billResult.getMsg());
        }
        return Result.success();
    }

    /**
     * 根据总价计算应收价格，减去会员积分和优惠券
     *
     * @param shipOrder
     * @param orderAmount
     */
    private void buildReceivableAmount(ShipOrder shipOrder, BigDecimal orderAmount) {
        BigDecimal receivableAmount = new BigDecimal(orderAmount.toString());
        //计算应收价格-是否使用积分
        if (shipOrder.getUsingPoints() != null) {
            BigDecimal usingPoints = new BigDecimal(String.valueOf(shipOrder.getUsingPoints()));
            // 校验会员积分是否充足
//            checkMemberPoints(shipOrder, usingPoints);
            //计算应收价格-计算积分
            BigDecimal usingPointsCNY = usingPoints.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
            //人民币兑港币
            BigDecimal crmExchangeRate = getCrmExchangeRateByName(Currency.CNY.getSymbol());
            BigDecimal usingPointsHKD = usingPointsCNY.multiply(crmExchangeRate);
            if (receivableAmount.compareTo(usingPointsHKD) < 0) {
                // 总价减去积分价后为负数，不予许提交
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60007);
            }
            receivableAmount = receivableAmount.subtract(usingPointsHKD);
        }
        //计算应收价格-计算推广码（优惠券）
//        if (shipOrder.getCouponId() != null) {
//            // do something 推广码接口未写完，等待中
////            OperatePromotionQueryReq operatePromotionQueryReq = new OperatePromotionQueryReq();
////            operatePromotionQueryReq.setId(airportExpressOrder.getCouponId());
////            Result<OperatePromotionQueryDTO> operatePromotionQueryDTOResult = operatePromotionService.query(operatePromotionQueryReq);
//        }
        shipOrder.setOrderAmount(receivableAmount);
    }


    @Override
    public Result cancelOrderBeforePay(ShipCancelOrderReq cancelOrderReq) {
        ShipOrder shipOrder = shipOrderMapper.selectById(cancelOrderReq.getOrderId());
        shipOrder.setPaymentStatus(OrderPaymentStatus.ALREADY_CANCEL.getCode());
        shipOrder.setScheduledStatus(null);
        shipOrder.setCancelStatus(null);
        shipOrder.setGmtModified(LocalDateTime.now());
        shipOrder.setCancelReason(cancelOrderReq.getRefundReason());
        shipOrderMapper.updateById(shipOrder);

        return Result.success(cancelOrderReq.getOrderId());
    }

    @Override
    public Result cancelApprove(ShipCancelOrderReq cancelOrderReq) {
        ShipOrder shipOrder = shipOrderMapper.selectById(cancelOrderReq.getOrderId());
        if (shipOrder == null) {
            throw new BusinessException(SystemError.SHIP_PRODUCT_11006);
        }
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(cancelOrderReq.getShipOrderRefundCancelReqList())) {
            // 退款记录不能为空
            throw new BusinessException(SystemError.SHIP_PRODUCT_11031);
        }
        //审批状态 ，取消订单审批通过或正在审批中，不允许重复操作
        if(ApprovalStatus.REVIEWING.getCode().equals(shipOrder.getCancelStatus()) ||
                ApprovalStatus.REVIEW_YES.getCode().equals(shipOrder.getCancelStatus())){
            throw new BusinessException(SystemError.LOCAL_FUN_18013);
        }
        if (shipOrder.getPaymentStatus() == OrderPaymentStatus.ALREADY_PAYMENT.getCode() && shipOrder.getScheduledStatus() == OrderScheduledStatus.RESERVE_SUCCESS.getCode()) {
            // 已经付款，预订成功，不退不改
            throw new BusinessException(SystemError.SHIP_PRODUCT_11030);
        }

        //获取用户信息
        UserDTO userDTO = getUserDTO();

        //发起取消订单审批
        Result<ApprovalStartDTO> result = iSysApprovalService.start(SystemBusinessType.SHIP_TICKET.getCode(),
                SysApprovalType.CANCEL_SHIP.getCode(),shipOrder.getId(),userDTO.getId(),null, "2");

        //更新订单取消审批状态和退款审批状态
        if(result.isSuccess()){
            shipOrder.setCancelStatus(ApprovalStatus.REVIEWING.getCode());
            shipOrder.setGmtModified(LocalDateTime.now());
            shipOrder.setCancelReason(cancelOrderReq.getRefundReason());
            shipOrderMapper.updateById(shipOrder);

            LocalDateTime nowLocalDateTime = LocalDateTime.now();
            List<ShipOrderRefund> shipOrderRefundList = EntityUtil.copyList(cancelOrderReq.getShipOrderRefundCancelReqList(), ShipOrderRefund.class);
            for (ShipOrderRefund shipOrderRefund : shipOrderRefundList) {
                shipOrderRefund.setRefundNumber(OperateNumberGenerateUtil.generateRefundNumber(nowLocalDateTime));
                shipOrderRefund.setOrderId(cancelOrderReq.getOrderId());
                shipOrderRefund.setStatus(ApprovalStatus.REVIEWING.getCode());
                shipOrderRefund.setIsDeleted(IsDeletedCode.NO.getCode());
                shipOrderRefund.setGmtCreate(nowLocalDateTime);
                shipOrderRefundMapper.insert(shipOrderRefund);
            }
        }else {
            Result result1 = new Result();
            result1.setCode(result.getCode());
            result1.setMsg(result.getMsg());
            return result1;
        }
        return Result.success(Long.valueOf(shipOrder.getId()));
    }

    @Override
    public Result<AppShipOrderInfoDTO> queryOrderDetail(Long id) {
        ShipOrder shipOrder = baseMapper.selectById(id);
        if(shipOrder == null){
            throw new BusinessException(SystemError.SHIP_PRODUCT_11032);
        }
        AppShipOrderInfoDTO dtoDetail = AppShipOrderInfoDTO.builder().orderNumber(shipOrder.getOrderNumber())
                .orderAmount(shipOrder.getOrderAmount()).gmtCreate(shipOrder.getGmtCreate())
                .salesMethods(shipOrder.getSalesMethods()).paymentStatus(shipOrder.getPaymentStatus()).scheduledStatus(shipOrder.getScheduledStatus())
                .cancelStatus(shipOrder.getCancelStatus()).businessType("船票").payExpireDate(shipOrder.getPayExpireDate())
                .productType(shipOrder.getProductType()).source(shipOrder.getSource()).salesmanName(shipOrder.getSalesmanName()).contactMobileAreaCode(shipOrder.getContactMobileAreaCode())
                .clientType(shipOrder.getAgencyCompany()).contactName(shipOrder.getContactName()).contactMobile(shipOrder.getContactMobile()).contactEmail(shipOrder.getContactEmail())
                .remark(shipOrder.getRemark()).tripType(shipOrder.getTripType()).receivableAmount(shipOrder.getReceivableAmount()).refundedAmount(shipOrder.getRefundedAmount()).build();


        //订单状态
        if (shipOrder.getPaymentStatus() == null || OrderPaymentStatus.UN_PAYMENT.getCode().equals(shipOrder.getPaymentStatus())) {
            dtoDetail.setOrderStatus(OrderStatus.UN_PAYMENT.getCode());
        } else if (OrderScheduledStatus.CONFIRM_RESERVE.getCode().equals(shipOrder.getScheduledStatus())) {
            dtoDetail.setOrderStatus(OrderStatus.CONFIRM_RESERVE.getCode());
        } else if (OrderScheduledStatus.RESERVE_SUCCESS.getCode().equals(shipOrder.getScheduledStatus())) {
            dtoDetail.setOrderStatus(OrderStatus.RESERVE_SUCCESS.getCode());
        } else if (OrderScheduledStatus.RESERVE_FAIL.getCode().equals(shipOrder.getScheduledStatus())) {
            dtoDetail.setOrderStatus(OrderStatus.RESERVE_FAIL.getCode());
        } else if (OrderPaymentStatus.ALREADY_CANCEL.getCode().equals(shipOrder.getPaymentStatus())) {
            dtoDetail.setOrderStatus(OrderStatus.ALREADY_CANCEL.getCode());
            dtoDetail.setCancelReason(shipOrder.getCancelReason());
        }

        //去程航線信息
        setSingleRouteInfo(dtoDetail,shipOrder);
        if(shipOrder.getTripType() == 2){
            //返程航線信息
            setBackRouteInfo(dtoDetail,shipOrder);
        }

        //是否有购买保险
        dtoDetail.setHasInsurance(0);
        Integer count = shipOrderInsuranceMapper.selectCount(Wrappers.<ShipOrderInsurance>lambdaQuery().eq(ShipOrderInsurance::getOrderId, shipOrder.getId()));
        if(count > 0){
            dtoDetail.setHasInsurance(1);
        }
        return Result.success(dtoDetail);
    }

    /**
     * 去程航線信息
     * @param dtoDetail
     * @param shipOrder
     */
    private void setSingleRouteInfo(AppShipOrderInfoDTO dtoDetail, ShipOrder shipOrder) {
        String productId = shipOrder.getProductId();
        if(StringUtil.isEmpty(productId)) {
            return;
        }
        String[] productIds = productId.split(",");
        if(productIds.length < 1){
            return;
        }
        Long id = Long.valueOf(productIds[0]);
        QueryWrapper<ShipOrderRoute> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShipOrderRoute::getOrderId,shipOrder.getId());
        queryWrapper.lambda().eq(ShipOrderRoute::getProductId,id);
        ShipOrderRoute shipOrderRoute = shipOrderRouteMapper.selectOne(queryWrapper);
        if(shipOrderRoute != null){
            if(shipOrderRoute.getCompanyType() == 1L){
                dtoDetail.setCompanyName1("信德船舶");
            }else {
                dtoDetail.setCompanyName1("珠江船舶");
            }
            dtoDetail.setRouteName1(shipOrderRoute.getRouteName());
            dtoDetail.setArrCityName1(shipOrderRoute.getArrCityName());
            dtoDetail.setDepCityName1(shipOrderRoute.getDepCityName());
            dtoDetail.setDepPlaceName1(shipOrderRoute.getDepPlaceName());
            dtoDetail.setArrPlaceName1(shipOrderRoute.getArrPlaceName());
            dtoDetail.setCabinClassName1(shipOrderRoute.getCabinClassName());
            dtoDetail.setVoyage1(shipOrderRoute.getVoyage());
            //出发日期
            if(shipOrderRoute.getDepTime() != null){
                dtoDetail.setStartDate1(shipOrderRoute.getDepTime().toLocalDate());
            }
            dtoDetail.setShipTypeName1(shipOrderRoute.getShipTypeName());
            //开船时间
            dtoDetail.setStartTime1(shipOrderRoute.getBeginTime());

            ShipProductReserveInfoDTO reserveInfoDTO = iAppShipProductService.queryShipProductReserveDetail(id);
            if(reserveInfoDTO != null){
                dtoDetail.setTicketCollectionType1(reserveInfoDTO.getTicketCollectionType());
                dtoDetail.setTicketCollection1(reserveInfoDTO.getTicketCollection());
                dtoDetail.setExchangeMethod1(reserveInfoDTO.getExchangeMethod());
            }
        }
    }

    /**
     *
     *返程航線信息
     * @param dtoDetail
     * @param shipOrder
     */
    private void setBackRouteInfo(AppShipOrderInfoDTO dtoDetail, ShipOrder shipOrder) {
        String productId = shipOrder.getProductId();
        if(StringUtil.isEmpty(productId)) {
            return;
        }
        String[] productIds = productId.split(",");
        if(productIds.length < 2){
            return;
        }
        Long id = Long.valueOf(productIds[1]);
        QueryWrapper<ShipOrderRoute> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShipOrderRoute::getOrderId,shipOrder.getId());
        queryWrapper.lambda().eq(ShipOrderRoute::getProductId,id);
        ShipOrderRoute shipOrderRoute = shipOrderRouteMapper.selectOne(queryWrapper);
        if(shipOrderRoute != null){
            if(shipOrderRoute.getCompanyType() == 1L){
                dtoDetail.setCompanyName2("信德");
            }else {
                dtoDetail.setCompanyName2("珠江");
            }
            dtoDetail.setRouteName2(shipOrderRoute.getRouteName());
            dtoDetail.setArrCityName2(shipOrderRoute.getArrCityName());
            dtoDetail.setDepCityName2(shipOrderRoute.getDepCityName());
            dtoDetail.setDepPlaceName2(shipOrderRoute.getDepPlaceName());
            dtoDetail.setArrPlaceName2(shipOrderRoute.getArrPlaceName());
            dtoDetail.setCabinClassName2(shipOrderRoute.getCabinClassName());
            dtoDetail.setVoyage2(shipOrderRoute.getVoyage());
            //出发日期
            if(shipOrderRoute.getDepTime() != null){
                dtoDetail.setStartDate2(shipOrderRoute.getDepTime().toLocalDate());
            }
            dtoDetail.setShipTypeName2(shipOrderRoute.getShipTypeName());
            //开船时间
            dtoDetail.setStartTime2(shipOrderRoute.getBeginTime());

            ShipProductReserveInfoDTO reserveInfoDTO = iAppShipProductService.queryShipProductReserveDetail(id);
            if(reserveInfoDTO != null){
                dtoDetail.setTicketCollectionType1(reserveInfoDTO.getTicketCollectionType());
                dtoDetail.setTicketCollection1(reserveInfoDTO.getTicketCollection());
                dtoDetail.setExchangeMethod1(reserveInfoDTO.getExchangeMethod());
            }
        }

    }

    private List<BillAddCollectionReq> obtainBillCollection(Long id, ShipOrder shipOrder, ShipOrderCollection shipOrderCollection, AppShipOrderCollectionReq appShipOrderCollectionReq, List<String> resourceInfoList, List<Long> productIds) {
        List<BillAddCollectionReq> billAddCollectionList = Lists.newArrayList();
        //获取航班信息
        BillAddCollectionReq billAddCollectionReq = new BillAddCollectionReq();
        //        单号
        billAddCollectionReq.setBillNumber(shipOrderCollection.getCollectionNumber());
        //        业务类型
        billAddCollectionReq.setBusinessType(SystemBusinessType.SHIP_TICKET.getCode());
        //        收款方式ID
        billAddCollectionReq.setCollectionWayId(shipOrderCollection.getCollectionWayId());
        //        收款方式
        billAddCollectionReq.setCollectionWayName(shipOrderCollection.getCollectionWay());
        //        收款类型ID
        billAddCollectionReq.setCollectionTypeId(CollectionTypeIdCode.FULL.getCode());
        //        收款类型
        billAddCollectionReq.setCollectionTypeName(CollectionTypeIdCode.FULL.getMsg());
        //        收款金额
        billAddCollectionReq.setCollectionAmount(shipOrderCollection.getCollectionAmount());
        //        币种ID
        billAddCollectionReq.setCurrencyId(shipOrderCollection.getCurrencyId());
        //        币种名称
        billAddCollectionReq.setCurrencyName(shipOrderCollection.getCurrency());
        //        汇率
        // 获取对应汇率，计算支付金额
        BigDecimal exchangeRate = iMainDataCurrencyService.getExchangeRate(shipOrderCollection.getCurrency(), CurrencyRateExchangeConstant.MARKET_EXCHANGE_RATE_);

        billAddCollectionReq.setExchangeRate(exchangeRate.doubleValue());
        //        收款时间
        billAddCollectionReq.setCollectionTime(LocalDateTime.now());
        //        收款凭证JSON
        try { //避免出行json格式不对导致异常
            billAddCollectionReq.setCollectionVoucherJsonList(
                    JSONArray.parseArray(shipOrderCollection.getCollectionCertificateJson(), FileJson.class)
            );
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //        销售单号
        billAddCollectionReq.setSaleOrderNumber(shipOrder.getOrderNumber());
        //        销售单ID
        billAddCollectionReq.setSaleOrderId(id);
        //        产品ID
        billAddCollectionReq.setProductId(productIds);
        //        产品编号/团号
//            billAddCollectionReq.setProductNumber(productNumbers);
        //        产品名称
//            billAddCollectionReq.setProductName();
        //        资源信息
        billAddCollectionReq.setResourceInfo(resourceInfoList);
        //TODO
        //        销售人员ID
//        billAddCollectionReq.setSaleUserId(user.getId());
//        //        销售人员名称
//        billAddCollectionReq.setSaleUserName(user.getNickname());
//        //        销售部门ID
//        billAddCollectionReq.setSaleDeptId(userToekn.getDeptId());
//        //        用户ID
//        billAddCollectionReq.setUserId(user.getId());
        billAddCollectionList.add(billAddCollectionReq);
        return billAddCollectionList;
    }

    /**
     * 保存收款记录
     * @param id
     * @param nowLocalDateTime
     * @param appShipOrderCollectionReq
     * @param userDTO
     */
    private ShipOrderCollection addOrderCollection(Long id, LocalDateTime nowLocalDateTime, AppShipOrderCollectionReq appShipOrderCollectionReq, UserDTO userDTO) {
        ShipOrderCollection shipOrderCollection = new ShipOrderCollection();
        shipOrderCollection.setCollectionAmount(appShipOrderCollectionReq.getPayAmount());
        shipOrderCollection.setCollectionNumber(ShipOrderGenerator.getCollectionNumber());
        shipOrderCollection.setOrderId(id);
        shipOrderCollection.setCreateId(userDTO.getId());
        shipOrderCollection.setGmtCreate(nowLocalDateTime);
        shipOrderCollection.setCollectionWay(appShipOrderCollectionReq.getPayMethod());
        shipOrderCollectionMapper.insert(shipOrderCollection);
        return shipOrderCollection;
    }


    /**
     * 下供应商预订单
     * @param shipOrder
     * @param shipProductDetailDTO
     * @param supplierSize
     * @param userDTO
     */
    private void extracted(ShipOrder shipOrder, ShipProductDetailDTO shipProductDetailDTO, Set<String> supplierSize, UserDTO userDTO) {
        //供应商预订单
        SupplierOrderSystemShipAddReq supplierOrderSystemShipAddReq = new SupplierOrderSystemShipAddReq();
//        订单类型
        supplierOrderSystemShipAddReq.setOrderType(null);
//        外挂单出票类型(1:门店出票, 2:后台出票)
        supplierOrderSystemShipAddReq.setTicketMode(null);
//        所属团期ID
        supplierOrderSystemShipAddReq.setScheduleId(null);
//        供应商ID不能为空供应商ID
        supplierOrderSystemShipAddReq.setSupplierId(Long.valueOf(shipProductDetailDTO.getSupplierId()));
//        供应商名称不能为空供应商名称
        supplierOrderSystemShipAddReq.setSupplierName(shipProductDetailDTO.getSupplierName());
//        供应商订单类型不能为空供应商订单类型(1:普通订单, 2:内部挂账订单)
        supplierOrderSystemShipAddReq.setSupplierOrderType("1");
//        供应商销售编号 / 部门ID不能为空 供应商销售编号 / 部门ID(根据 '供应商订单编号' 显示，1：供应商销售编号，2：部门ID)
        supplierOrderSystemShipAddReq.setOriginalSaleNumber(null);
//        业务类型不能为空业务类型, 枚举SystemBusinessType
        supplierOrderSystemShipAddReq.setBusinessType(SystemBusinessType.SHIP_TICKET.getCode());
//        预订类型不能为空预订类型, 枚举SupplierReserveTypeEnum
        supplierOrderSystemShipAddReq.setReserveTypeId(SupplierReserveTypeEnum.SHIP.getId());
//        产品类型不能为空产品类型，枚举ProductType
        supplierOrderSystemShipAddReq.setProductType(shipProductDetailDTO.getProductSource());
//        资源所属部门ID(当前用户部门ID)
        supplierOrderSystemShipAddReq.setDepartmentId(null);
//        资源所属部门
        supplierOrderSystemShipAddReq.setDepartment(null);
//        供应商联络人姓名
        /*supplierOrderSystemShipAddReq.setSupplierContactName(null);
//        供应商联络人电话区号
        supplierOrderSystemShipAddReq.setSupplierContactMobileAreaCode(null);
//        供应商联络人电话
        supplierOrderSystemShipAddReq.setSupplierContactMobile(null);
//        供应商联络人传真
        supplierOrderSystemShipAddReq.setSupplierContactFax(null);
//        供应商联络人邮箱
        supplierOrderSystemShipAddReq.setSupplierContactEmail(null);*/
//        销售单号(通用) 不能为空销售单号(通用)
        supplierOrderSystemShipAddReq.setSaleNumber(shipOrder.getOrderNumber());
//        产品编号(通用) 不能为空产品编号(通用)
        supplierOrderSystemShipAddReq.setProductNumber(shipProductDetailDTO.getCode());
//        产品名称(通用) 不能为空产品名称(通用)
        supplierOrderSystemShipAddReq.setProductName(shipProductDetailDTO.getCode());
//        总金额不能为空总金额
        supplierOrderSystemShipAddReq.setTotalFee(shipOrder.getOrderAmount());

        MainDataCurrencyQueryDTO currencyEntity = iMainDataCurrencyService.getExchangeCurrencyEntity("HKD", CurrencyRateExchangeConstant.MARKET_EXCHANGE_RATE_);
//        币种ID不能为空币种ID
        supplierOrderSystemShipAddReq.setCurrencyId(currencyEntity.getId());
//        币种不能为空币种
        supplierOrderSystemShipAddReq.setCurrency("HKD");
//        应付金额不能为空应付金额
        supplierOrderSystemShipAddReq.setPayableAmount(shipOrder.getReceivableAmount());
//        付款类型ID不能为空付款类型ID, 当值 '内部挂账' 时 'scheduleId' 不能为空,,枚举PayRefundMethod
//        supplierOrderSystemShipAddReq.setPayTypeId(null);
////        付款类型
//        supplierOrderSystemShipAddReq.setPayType(null);
////        供应商期望付款时间
//        supplierOrderSystemShipAddReq.setExpectedPayTime(null);
//        附件文件JSON
        supplierOrderSystemShipAddReq.setFilesJson(null);
//        确认状态
        supplierOrderSystemShipAddReq.setConfirmStatus(shipOrder.getScheduledStatus());
//        确认时间
        supplierOrderSystemShipAddReq.setConfirmTime(null);
//        供应商订单号
        supplierOrderSystemShipAddReq.setSupplierOrderNumber(null);
//        提交结算状态
//        supplierOrderSystemShipAddReq.setSubmitSettleStatus(null);
//        使用资源编号
        supplierOrderSystemShipAddReq.setResourceNumber(null);
//        使用资源产品名称
        supplierOrderSystemShipAddReq.setResourceProductName(null);
//        备注
        supplierOrderSystemShipAddReq.setRemark(null);
        supplierOrderSystemShipAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode());
//        船信息不能为空船信息
        SupplierSystemOrderShipAddReq supplierSystemOrderShipAddReq = new SupplierSystemOrderShipAddReq();
        supplierSystemOrderShipAddReq.setSupplierSystemOrderShipTicketAddReqList(buildShipDetail(shipProductDetailDTO,shipOrder));
        supplierOrderSystemShipAddReq.setSupplierSystemOrderShipAddReq(supplierSystemOrderShipAddReq);
        //TODO
        iSupplierOrderService.addSystemShip(supplierOrderSystemShipAddReq, userDTO.getId());
        //产品是同一个供应商只下一次供应商预订单
        if(!StringUtils.isEmpty(shipProductDetailDTO.getSupplierId())){
            supplierSize.add(shipProductDetailDTO.getSupplierId());
        }
    }


    /**
     * 构建产品详情列表
     * @param shipProductDetailDTO
     * @param shipOrder
     * @return
     */
    private List<SupplierSystemOrderShipTicketAddReq> buildShipDetail(ShipProductDetailDTO shipProductDetailDTO, ShipOrder shipOrder) {
        List<SupplierSystemOrderShipTicketAddReq> supplierSystemOrderShipTicketAddReqList = new ArrayList<>();
        SupplierSystemOrderShipTicketAddReq req = new SupplierSystemOrderShipTicketAddReq();
        req.setShipId(shipProductDetailDTO.getId());
        req.setOrderId(shipOrder.getId());
        req.setTravelType(shipOrder.getTripType());

        Map<String,String> goMap = Maps.newHashMap();
        goMap.put("go",shipProductDetailDTO.getDepPlaceName());
        req.setGoLocationJson(JSON.toJSONString(goMap));
        Map<String,String> goMap2 = Maps.newHashMap();
        goMap.put("go",shipProductDetailDTO.getArrPlaceName());
        req.setDesLocationJson(JSON.toJSONString(goMap2));

        req.setBusNumber(shipProductDetailDTO.getVoyage());
        req.setStartTime(shipProductDetailDTO.getDepTimeStart());
        req.setEndTime(shipProductDetailDTO.getArrTimeStart());
        req.setTaxAmount(shipProductDetailDTO.getOtherFeePrice());

        ShipPriceReq shipPriceReq = new ShipPriceReq();
        shipPriceReq.setProductId(shipProductDetailDTO.getId());
        shipPriceReq.setQueryDate(shipOrder.getGmtCreate().toLocalDate());
        QueryWrapper<ShipOrderTourist> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShipOrderTourist::getOrderId,shipOrder.getId());
        List<ShipOrderTourist> shipOrderTourists = shipOrderTouristMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(shipOrderTourists)){
//            Result<Map<Integer, List<ShipBaseInfoDTO>>> mapResult = iShipProductService.queryShipPriceByDate(shipPriceReq);
            shipOrderTourists.forEach(entity->{
//                if(mapResult.getData()!=null){
//                    List<ShipBaseInfoDTO> orDefault = mapResult.getData().getOrDefault(entity.getTouristTypeId(), null);
//                    if(CollectionUtil.isNotEmpty(orDefault)){
//                        ShipBaseInfoDTO shipBaseInfoDTO = orDefault.stream().findFirst().orElse(null);
//                        if(shipBaseInfoDTO != null){
//                            //成本价
//                            req.setSinglePrice(shipBaseInfoDTO.getCostPrice());
//                            //税费
//                            req.setTaxAmount(shipBaseInfoDTO.getTaxFee());
//                        }
//                    }
//                }
                req.setTouristId(entity.getId());
                req.setTouristName(entity.getTouristName());
                supplierSystemOrderShipTicketAddReqList.add(req);
            });
        }
        return supplierSystemOrderShipTicketAddReqList;
    }
    /**
     * 校验订单数据
     *
     * @param shipOrder
     * @param nowLocalDateTime
     * @param appShipOrderCollectionReq
     * @return
     */
    private Result checkOrderData(ShipOrder shipOrder, LocalDateTime nowLocalDateTime, AppShipOrderCollectionReq appShipOrderCollectionReq) {
        //1.支付超时
        if (nowLocalDateTime.isAfter(shipOrder.getPayExpireDate())) {
            // 支付超时
            return Result.failed(SystemError.SHIP_PRODUCT_11028);
        }

        // 收款金额
        BigDecimal amountCountHKD = appShipOrderCollectionReq.getPayAmount();
        //2.校验应收价格
        if(amountCountHKD.compareTo(shipOrder.getOrderAmount()) < 0){
            return  Result.failed(SystemError.SHIP_PRODUCT_11050);
        }
        return null;
    }

    /**
     * 银行优惠工具类
     */
    private BigDecimal getAmountByBankReference(ShipOrder shipOrder, Long unionpayDiscountId) {
        OperateBankConformQueryReq operateBankConformQueryReq = new OperateBankConformQueryReq();
        operateBankConformQueryReq.setId(unionpayDiscountId);
        Result<OperateBankPreferenceQueryDTO> operateBankPreferenceQueryDTOResult = operateBankPreferenceService.queryConform(operateBankConformQueryReq);
        if (!operateBankPreferenceQueryDTOResult.isSuccess()) {
            // 校验银行优惠不满足条件
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60018);
        }
        OperateBankPreferenceQueryDTO bankQueryDto = operateBankPreferenceQueryDTOResult.getData();
        if (bankQueryDto.getDiscountType() == 1) {
            // 校验应收价格是否符合满减优惠
            if (shipOrder.getReceivableAmount().compareTo(bankQueryDto.getFullAmount()) >= 0) {
                return bankQueryDto.getReductionAmount();
            } else {
                // 校验银行优惠不满足条件
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60018);
            }
        } else {
            // 使用百分比优惠
            BigDecimal currentAmount = shipOrder.getReceivableAmount().multiply(new BigDecimal(String.valueOf(bankQueryDto.getDiscountPercent())));
            return currentAmount.compareTo(bankQueryDto.getMaxDiscount()) > 0 ? bankQueryDto.getMaxDiscount() : currentAmount;
        }
    }

    /**
     * 根据币种名称获取汇率
     *
     * @param currencySy
     * @return
     */
    private BigDecimal getCrmExchangeRateByName(String currencySy) {
        MainDataCurrencyListReq mainDataCurrencyListReq = new MainDataCurrencyListReq();
        mainDataCurrencyListReq.setName(currencySy);
        PageResponse<MainDataCurrencyListDTO> list = iMainDataCurrencyService.list(mainDataCurrencyListReq);
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(list.getRecords())) {
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60003);
        }
        return list.getRecords().get(0).getCrmExchangeRate();
    }

    private void saveSaleRecord(Long orderId, ShipOrderRouteProductReq shipOrderRouteProductReq, Long productId,Long channelId) {
        /**保存产品库存售卖记录body*/
        ShipProductSaleRecordReq shipProductSaleRecordReq = new ShipProductSaleRecordReq();
        shipProductSaleRecordReq.setId(SnowflakeIdWorker.nextId());
        shipProductSaleRecordReq.setOrderId(orderId);
        shipProductSaleRecordReq.setProductId(productId);
        shipProductSaleRecordReq.setSalesDate(shipOrderRouteProductReq.getStartDate());
        shipProductSaleRecordReq.setSoldNumber(shipOrderRouteProductReq.getTicketNumber());
        //1:自营 2:代理商 3:官方渠道 4:第三方
        shipProductSaleRecordReq.setChannel(3);
        //1 线上 2线下
        shipProductSaleRecordReq.setLine(2);
        ////备注要加权限
//        shipProductSaleRecordReq.setCheckType(1);
        shipProductSaleRecordReq.setCustomId(channelId);
//        shipProductSaleRecordReq.setCustomName(user.getUsername());
        iShipProductSaleRecordService.insertRecord(shipProductSaleRecordReq, null);
    }


    private void saveOrderInfo(AppShipOrderReq shipOrderReq, AppShipOrderAmountItem shipOrderAmountItem, int adultTotalNumber, int childrenTotalNumber, Long orderId, String productIds, AtomicInteger tripTypeFlag, List<ShipOrderDetailListDTO> shipAllOrderDetailList) {
        BigDecimal serviceAmount = shipOrderAmountItem.getServiceAmount();
        BigDecimal totalAmount = shipOrderAmountItem.getTotalAmount();
        /**保存订单信息*/
        ShipOrder shipOrder = new ShipOrder();
        BeanUtils.copyProperties(shipOrderReq, shipOrder);
        //组装订单
        shipOrder.setId(orderId);
        shipOrder.setTripType(tripTypeFlag.get());//订单行程类型 1.单程 2往返
        shipOrder.setProductId(productIds);
        LocalDateTime now = LocalDateTime.now();
        shipOrder.setGmtCreate(now);
        shipOrder.setGmtModified(now);
        shipOrder.setIsDeleted(ShipConstants.NOT_DELETE);

        UserDTO userDTO = getUserDTO();
        shipOrder.setCreateId(userDTO.getId());
        //销售编号
        shipOrder.setOrderNumber(buildProductNumber(userDTO, LocalDateTime.now()));

        // 计算付款到期时间,+30分钟
        shipOrder.setPayExpireDate(LocalDateTime.now().plusMinutes(30));
        //单服务费*面票数 次字段存稅費
        serviceAmount = serviceAmount.multiply(new BigDecimal(adultTotalNumber + childrenTotalNumber));
        shipOrder.setServiceFee(serviceAmount);
        //应收金额
        shipOrder.setReceivableAmount(totalAmount);
        //最终订单金额
        buildReceivableAmount(shipOrder,totalAmount);
        shipOrder.setContactName(shipOrderReq.getContactName());
        shipOrder.setPaymentStatus(OrderPaymentStatus.UN_PAYMENT.getCode()); //未付款
        shipOrder.setSalesmanId(userDTO.getId());
        // 1:中旅H5,2:APP-Android,3:APP-中旅iOS,4:PC-中旅網"
        Integer source = shipOrderReq.getChannelId() == 1 ? OrderSource.H5.getCode() : shipOrderReq.getChannelId() == 2 ? OrderSource.APP_ANDROID.getCode() : shipOrderReq.getChannelId() == 3 ? OrderSource.APP_IOS.getCode() : OrderSource.PC_NET.getCode();
        shipOrder.setSource(source);
        shipOrder.setSalesmanName(userDTO.getUsername());
        shipOrder.setSalesMethods(1);//销售方式(1：单品销售 2：打包销售)
        shipOrder.setProductType(1);//产品类型(1手工单，2外挂单)
        shipOrder.setCreateId(userDTO.getId());
        shipOrder.setOrderDetails(JSONUtil.toJsonStr(shipAllOrderDetailList));
        shipOrder.setGmtCreate(LocalDateTime.now());

        if(shipOrderAmountItem.getDepCity().length() > 0){
            shipOrder.setDepCityName(shipOrderAmountItem.getDepCity().substring(0,shipOrderAmountItem.getDepCity().length()-1));
        }
        if(shipOrderAmountItem.getArrCity().length() > 0){
            shipOrder.setArrCityName(shipOrderAmountItem.getArrCity().substring(0,shipOrderAmountItem.getArrCity().length()-1));
        }
        if(shipOrderAmountItem.getDepPlace().length() > 0){
            shipOrder.setDepPlaceName(shipOrderAmountItem.getDepPlace().substring(0,shipOrderAmountItem.getDepPlace().length()-1));
        }
        if(shipOrderAmountItem.getArrPlace().length() > 0){
            shipOrder.setArrPlaceName(shipOrderAmountItem.getArrPlace().substring(0,shipOrderAmountItem.getArrPlace().length()-1));
        }
        if(shipOrderAmountItem.getVoyage().length() > 0){
            shipOrder.setVoyage(shipOrderAmountItem.getVoyage().substring(0,shipOrderAmountItem.getVoyage().length()-1));
        }
        if(!StringUtils.isEmpty(shipOrderAmountItem.getCabinClassName())){
            shipOrder.setCabinClassName(shipOrderAmountItem.getCabinClassName());
        }
        if(!StringUtils.isEmpty(shipOrderAmountItem.getCompanyType())){
            shipOrder.setCompanyType(shipOrderAmountItem.getCompanyType().substring(0,shipOrderAmountItem.getCompanyType().length()-1));
        }
        shipOrderMapper.insert(shipOrder);


//        //过期取消订单 API定时任务
//        try {
//            // 下单完成后调用任务执行如果未付款则超时失效订单操作
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("id", orderId);
//            // 延迟时间,单位毫秒,1800000L=30分钟后执行
//            long delayMS = 1800000L;
//            OhMyClient taskClient = new OhMyClient(domain, appName, password);
//            ResultDTO<Long> resultTask = taskClient.runJob(jobId, jsonObject.toJSONString(), delayMS);
//
//            if (resultTask.isSuccess()) {
//                // 任务执行成功,过期时间*2是防止任务启动时redis数据已过期
//                redisTemplate.opsForValue().set(RedisConstants.ORDER_INSTANCELD_KEY + orderId, resultTask.getData(), delayMS * 2, TimeUnit.MILLISECONDS);
//            }
//        } catch (Exception e) {
//            log.error("当地玩乐订单-订单超时API任务错误");
//        }
    }

    /**
     * 获取用户信息
     * @return
     */
    private UserDTO getUserDTO() {
        //获取用户信息
        DispatchOrderRuleGetUserReq dispatchOrderRuleGetUserReq = new DispatchOrderRuleGetUserReq();
        dispatchOrderRuleGetUserReq.setBusinessTypeId(SystemBusinessType.SHIP_TICKET.getCode());
        dispatchOrderRuleGetUserReq.setCompanyType(CompanyType.HK_CT.getCode());
        Result<Long> result = iDispatchOrderRuleService.getDispatchUserId(dispatchOrderRuleGetUserReq);
        if (!result.isSuccess()) {
            log.error("【船票-订单】获取销售人失败:{},msg:{}", result.getCode(), result.getMsg());
            throw new BusinessException(SystemError.getDefined(result.getCode()));
        }
        UserDTO userDTO = iSysUserService.queryCacheUser(result.getData());

        if(userDTO == null){
            throw new BusinessException(SystemError.USER_1002);
        }
        return userDTO;
    }

//    /**
//     * 插入保险信息
//     * @param shipOrderReq  入参
//     * @param touristMap
//     * @param user          用户信息
//     * @param orderId       订单ID
//     */
//    private void saveInsuranceInfo(AppShipOrderReq shipOrderReq, Map<Long, ShipOrderTourist> touristMap, TokenUser user, Long orderId) {
//        /**保险信息*/
//        if (shipOrderReq.getBuyInsurance() != null && (shipOrderReq.getBuyInsurance().intValue() == NumberConstant.ONE.getValue().intValue())) {
//            List<ShipOrderInsuranceReq> shipOrderInsuranceReqList = shipOrderReq.getShipOrderInsuranceReqList();
//            if (CollectionUtil.isEmpty(shipOrderInsuranceReqList)) {
//                new BusinessException(SystemError.AIR_ORDER_15005);
//            }
//            for (ShipOrderInsuranceReq shipOrderInsuranceReq : shipOrderInsuranceReqList) {
//                ShipOrderInsurance shipOrderInsurance = new ShipOrderInsurance();
//                BeanUtils.copyProperties(shipOrderInsuranceReq, shipOrderInsurance);
//                shipOrderInsurance.setId(SnowflakeIdWorker.nextId());
//                shipOrderInsurance.setOrderId(orderId);
//                shipOrderInsurance.setCreateId(user.getId());
//
//                //保险信息
//                InsuranceDTO insuranceDto = notNull(iInsuranceService.detail(shipOrderInsuranceReq.getInsuranceId()), SystemError.CUSTOM_ORDER_4028);
//                shipOrderInsurance.setInsuranceNumber(insuranceDto.getApiCode());
//                shipOrderInsurance.setInsuranceName(insuranceDto.getName());
//
//                //保险报价
//                OfferReq offerReq = new OfferReq();
//                Offer offer = new Offer();
//                offer.setInsuranceId(shipOrderInsuranceReq.getInsuranceId());
//                offer.setRiskCode(null);
//                offer.setRationType(Assist.toInteger(insuranceDto.getRationType()));
//                offer.setStarDate(DateUtil.fmtLocalDate(shipOrderInsuranceReq.getInsuranceStartDate().toLocalDate(), "yyyy-MM-dd"));
//                offer.setEndDate(DateUtil.fmtLocalDate(shipOrderInsuranceReq.getInsuranceEndDate().toLocalDate(), "yyyy-MM-dd"));
//                offerReq.setData(offer);
//                try {
//                    OfferDTO offerDto = iInsuranceService.acciQuotation(offerReq);
//                    if (offerDto != null) {
//                        shipOrderInsurance.setInsurancePrice(offerDto.getPremium());
//                    }
//                } catch (Exception e) {
//                    log.error("保险服务调用异常");
//                }
//
//                //投保人
//                if(touristMap.get(shipOrderInsuranceReq.getPolicyHolderId()) != null){
//                    shipOrderInsurance.setPolicyHolderId(touristMap.get(shipOrderInsuranceReq.getPolicyHolderId()).getId());
//                    shipOrderInsurance.setPolicyHolderName(touristMap.get(shipOrderInsuranceReq.getPolicyHolderId()).getTouristName());
//                }
//                //被保人
//                if(StringUtil.isNotEmpty(shipOrderInsuranceReq.getInsuredPerson())){
//                    String[] insuredPersons = shipOrderInsuranceReq.getInsuredPerson().split(",");
//                    StringBuffer persons = new StringBuffer();
//                    for(String insuredPersonId : insuredPersons){
//                        if(touristMap.get(Long.valueOf(insuredPersonId)) != null){
//                            persons.append(touristMap.get(Long.valueOf(insuredPersonId)).getId() + ",");
//                        }
//                    }
//                    shipOrderInsurance.setInsuredPerson(persons.substring(0,persons.length()-1));
//                }
//                shipOrderInsurance.setGmtCreate(LocalDateTime.now());
//                shipOrderInsurance.setIsDeleted(IsDeletedCode.NO.getCode());
//                shipOrderInsuranceMapper.insert(shipOrderInsurance);
//            }
//        }
//    }

    /**
     * 保存航線信息
     * @param adultAmount
     * @param childrenAmount
     * @param adultTaxAmount
     * @param childrenTaxAmount
     * @param orderId
     * @param shipAllOrderDetailList
     * @param shipOrderRouteProductReq
     * @param shipReserveListDTO
     * @param adultNumber
     * @param childrenNumber
     * @param shipReserveDTO
     */
    private void saveShipOrderRoute(BigDecimal adultAmount, BigDecimal childrenAmount, BigDecimal adultTaxAmount, BigDecimal childrenTaxAmount, Long orderId, List<ShipOrderDetailListDTO> shipAllOrderDetailList, ShipOrderRouteProductReq shipOrderRouteProductReq, ShipReserveListDTO shipReserveListDTO, Integer adultNumber, Integer childrenNumber, ShipReserveDTO shipReserveDTO) {
        ShipOrderRouteReq shipOrderRouteReq = new ShipOrderRouteReq();
        BeanUtils.copyProperties(shipReserveDTO, shipOrderRouteReq);
        ShipOrderRoute shipOrderRoute = new ShipOrderRoute();
        BeanUtils.copyProperties(shipOrderRouteReq, shipOrderRoute);
        shipOrderRoute.setId(SnowflakeIdWorker.nextId());
        shipOrderRoute.setProductId(shipReserveListDTO.getId());
        shipOrderRoute.setOrderId(orderId);

        shipOrderRoute.setShipTypeName(shipReserveDTO.getShipTypeName());
        if(shipReserveDTO.getArrCityId() != null){
            shipOrderRoute.setArrCityId(Long.valueOf(shipReserveDTO.getArrCityId()));
        }
        if(shipReserveDTO.getDepCityId() != null){
            shipOrderRoute.setDepCityId(Long.valueOf(shipReserveDTO.getDepCityId()));
        }
        if(shipReserveDTO.getDepPlaceId() != null){
            shipOrderRoute.setDepPlaceId(Long.valueOf(shipReserveDTO.getDepPlaceId()));
        }
        if(shipReserveDTO.getArrPlaceId() != null){
            shipOrderRoute.setArrPlaceId(Long.valueOf(shipReserveDTO.getArrPlaceId()));
        }
        shipOrderRoute.setArrCityName(shipReserveDTO.getArrCityName());
        shipOrderRoute.setDepCityName(shipReserveDTO.getDepCityName());
        shipOrderRoute.setDepPlaceName(shipReserveDTO.getDepPlaceName());
        shipOrderRoute.setArrPlaceName(shipReserveDTO.getArrPlaceName());
        shipOrderRoute.setRouteName(shipReserveDTO.getRouteName());
        shipOrderRoute.setShipTypeName(shipReserveListDTO.getShipTypeName());

        if(shipReserveDTO.getCompanyType() != null){
            shipOrderRoute.setCompanyType(Long.valueOf(shipReserveDTO.getCompanyType()));
        }
        shipOrderRoute.setGmtCreate(LocalDateTime.now());
//        shipOrderRoute.setCreateId(user.getId());
        shipOrderRoute.setNumber(shipOrderRouteProductReq.getTicketNumber());
        shipOrderRoute.setIsDeleted(ShipConstants.NOT_DELETE);
        //开船时间
        shipOrderRoute.setBeginTime(shipReserveListDTO.getDepTime());
        //出发时间
        shipOrderRoute.setDepTime(DateUtil.toLocalDateTime(shipOrderRouteProductReq.getStartDate()));

        shipOrderRoute.setCabinClassName(Objects.isNull(shipReserveListDTO.getCabinClassName()) ? shipReserveListDTO.getCabinClassStr() : shipReserveListDTO.getCabinClassName());
        List<ShipOrderDetailListDTO> shipOrderDetailList = computeAmount(adultAmount, childrenAmount, adultTaxAmount, childrenTaxAmount, adultNumber, childrenNumber, "HDK");
        shipOrderRoute.setOrderDetails(JSONUtil.toJsonStr(shipOrderDetailList));
        shipAllOrderDetailList.addAll(shipOrderDetailList);
        shipOrderRouteMapper.insert(shipOrderRoute);
    }


    /**
     * 新增船票費和稅費
     * @param priceMap
     * @param taxMap
     * @param orderId
     */
    private void updateTouristPrice(Map<Long, Map<Integer, BigDecimal>> priceMap, Map<Long, BigDecimal> taxMap, Long orderId) {
        QueryWrapper<ShipOrderTourist> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShipOrderTourist::getOrderId,orderId);
        List<ShipOrderTourist> shipOrderTourists = shipOrderTouristMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(shipOrderTourists)){
            for(ShipOrderTourist tourist : shipOrderTourists){

                Integer touristTypeId = tourist.getTouristTypeId();
                StringBuffer price = new StringBuffer();
                priceMap.forEach((k,y)->{
                    //價格=成本價+加幅費
                    BigDecimal bigDecimal = y.get(touristTypeId);
                    Map<String,BigDecimal> map = Maps.newHashMap();
                    map.put("price",bigDecimal);
                    map.put("tax",taxMap.get(k));
                    //船票價格/稅費
                    price.append(JSON.toJSONString(map) + "/");
                });

                if(price.length()-1 > 0){
                    tourist.setTicketPrice(price.substring(0,price.length()-1));
                    shipOrderTouristMapper.updateById(tourist);
                }
            }
        }
    }

    /**
     * C+員工編號+月日4位+時分4位+4位隨機數字
     *
     * @param userId
     * @return
     */
    private String buildProductNumber(UserDTO userDTO, LocalDateTime nowLocalDateTime) {
        String employeeNumber = userDTO.getEmployeeNumber();
        String monthCode = org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(nowLocalDateTime.getMonthValue()), 2, "0");
        String dayCode = org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(nowLocalDateTime.getDayOfMonth()), 2, "0");
        String hourCode = org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(nowLocalDateTime.getHour()), 2, "0");
        String minuteCode = org.apache.commons.lang3.StringUtils.leftPad(String.valueOf(nowLocalDateTime.getMinute()), 2, "0");
        String randomNumber = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        StringBuilder orderNumberSb = new StringBuilder();
        orderNumberSb.append("C").append(employeeNumber).append(monthCode).append(dayCode).append(hourCode).append(minuteCode).append(randomNumber);
        return orderNumberSb.toString();
    }


    /**
     * 查询航线出发地、到达地
     * @param orderRouteProductReq
     * @param shipOrderRouteProductReq
     * @return
     */
    protected AppShipProductIsRecommendedReq queryShipInfo(ShipOrderRouteProductReq orderRouteProductReq, ShipOrderRouteProductReq shipOrderRouteProductReq) {
        AppShipProductIsRecommendedReq shipProductIsRecommendedReq = new AppShipProductIsRecommendedReq();
        //查询产品信息
        List<ConditionDTO> conditionReqList = Lists.newArrayListWithExpectedSize(5);
        ShipReservationOrderReq shipReservationOrderReq = new ShipReservationOrderReq();
        ConditionDTO conditionDTO = new ConditionDTO();
        conditionDTO.setId(shipOrderRouteProductReq.getProductId());
        conditionDTO.setQueryDate(shipOrderRouteProductReq.getStartDate());
        conditionReqList.add(conditionDTO);
        shipReservationOrderReq.setConditionReqList(conditionReqList);
        //只查询出发点、到达地等入参，此接口不可用作他用（价格计算的为B端的）
        List<ShipReservationGetOrderDTO> orderInfo = iAppShipProductService.getOrderInfo(shipReservationOrderReq);
        if(CollectionUtil.isNotEmpty(orderInfo)){
            ShipReservationGetOrderDTO dto = orderInfo.stream().findFirst().orElse(null);
            if(dto != null){
                shipProductIsRecommendedReq.setDepCityId(dto.getDepCityId());
                shipProductIsRecommendedReq.setArrCityId(dto.getArrCityId());
                shipProductIsRecommendedReq.setDepPlaceId(dto.getDepPlaceId());
                shipProductIsRecommendedReq.setId(Long.valueOf(shipOrderRouteProductReq.getProductId()));
                shipProductIsRecommendedReq.setArrPlaceId(dto.getArrPlaceId());
                shipProductIsRecommendedReq.setStartDate(shipOrderRouteProductReq.getStartDate());
                shipProductIsRecommendedReq.setCabinClass(String.valueOf(dto.getCabinClass()));
            }
        }
        shipProductIsRecommendedReq.setStartDate(orderRouteProductReq.getStartDate());
        shipProductIsRecommendedReq.setId(Long.valueOf(orderRouteProductReq.getProductId()));
        shipProductIsRecommendedReq.setTicketNumber(orderRouteProductReq.getTicketNumber());
        return shipProductIsRecommendedReq;
    }


    private List<ShipOrderDetailListDTO> computeAmount(BigDecimal adultAmount, BigDecimal childrenAmount, BigDecimal adultTaxAmount,
                                                       BigDecimal childrenTaxAmount, int adultNumber, int childrenNumber, String currency) {
        List<ShipOrderDetailListDTO> ShipOrderDetailList = new ArrayList<>();
        //合计成json
        if (adultNumber > 0) {
            List<ShipOrderDetailItemDTO> ShipOrderDetailItemList = new ArrayList<>();
            ShipOrderDetailItemDTO shipOrderDetailItemDTO = new ShipOrderDetailItemDTO();
            ShipOrderDetailListDTO shipOrderDetailListDTO = new ShipOrderDetailListDTO();
            shipOrderDetailListDTO.setTitle("成人船票总额");
            shipOrderDetailItemDTO.setTitle("成人票价");
            shipOrderDetailItemDTO.setNumber(adultNumber);
            shipOrderDetailItemDTO.setPrice(adultAmount);
            shipOrderDetailItemDTO.setCurrency(currency);
            ShipOrderDetailItemList.add(shipOrderDetailItemDTO);
            shipOrderDetailItemDTO = new ShipOrderDetailItemDTO();
            shipOrderDetailItemDTO.setTitle("稅與費用");
            shipOrderDetailItemDTO.setNumber(adultNumber);
            shipOrderDetailItemDTO.setPrice(adultTaxAmount);
            shipOrderDetailItemDTO.setCurrency(currency);
            ShipOrderDetailItemList.add(shipOrderDetailItemDTO);
            shipOrderDetailListDTO.setShipOrderDetailItemList(ShipOrderDetailItemList);
            ShipOrderDetailList.add(shipOrderDetailListDTO);
        }
        if (childrenNumber > 0) {
            List<ShipOrderDetailItemDTO> ShipOrderDetailItemList = new ArrayList<>();
            ShipOrderDetailItemDTO shipOrderDetailItemDTO = new ShipOrderDetailItemDTO();
            ShipOrderDetailListDTO shipOrderDetailListDTO = new ShipOrderDetailListDTO();
            shipOrderDetailListDTO.setTitle("小童船票总额");
            shipOrderDetailItemDTO.setTitle("小童票价");
            shipOrderDetailItemDTO.setNumber(childrenNumber);
            shipOrderDetailItemDTO.setPrice(childrenAmount);
            shipOrderDetailItemDTO.setCurrency(currency);
            ShipOrderDetailItemList.add(shipOrderDetailItemDTO);
            shipOrderDetailItemDTO = new ShipOrderDetailItemDTO();
            shipOrderDetailItemDTO.setTitle("稅與費用");
            shipOrderDetailItemDTO.setNumber(childrenNumber);
            shipOrderDetailItemDTO.setPrice(childrenTaxAmount);
            shipOrderDetailItemDTO.setCurrency(currency);
            ShipOrderDetailItemList.add(shipOrderDetailItemDTO);
            shipOrderDetailListDTO.setShipOrderDetailItemList(ShipOrderDetailItemList);
            ShipOrderDetailList.add(shipOrderDetailListDTO);
        }
        return ShipOrderDetailList;
    }

    /**
     * 保存旅客信息
     * @param productId
     * @param user
     * @param touristMap
     * @param shipOrderAmountItem
     * @param adultTotalNumber
     * @param childrenTotalNumber
     * @param orderId
     * @param shipOrderTouristList
     * @param touristSwitch
     * @param shipReserveListDTO
     * @param startDate
     * @param priceMap
     * @param channelId
     * @return
     */
    private ShipReserveDTO saveOrderTouristInfo(String productId, TokenUser user, Map<Long, ShipOrderTourist> touristMap, AppShipOrderAmountItem shipOrderAmountItem, AtomicInteger adultTotalNumber, AtomicInteger childrenTotalNumber, Long orderId, List<ShipOrderTouristReq> shipOrderTouristList, boolean touristSwitch, ShipReserveListDTO shipReserveListDTO, @NotNull(message = "出发时间不能为空") LocalDate startDate, Map<Long, Map<Integer, BigDecimal>> priceMap, Long channelId) {
        ShipReserveDTO shipReserveDTO = new ShipReserveDTO();
        BeanUtils.copyProperties(shipReserveListDTO, shipReserveDTO);
        Map<Integer,BigDecimal> map = Maps.newHashMap();

        //成本加+ 加辐费 + 税费 + 预订服务费
        BigDecimal adultPrice = new BigDecimal(0);
        BigDecimal childPrice = new BigDecimal(0);
        //成本加+ 加辐费
        BigDecimal beforeAdultPrice = new BigDecimal(0);
        BigDecimal beforeChildPrice = new BigDecimal(0);
        BigDecimal oldPrice = new BigDecimal(0);
        //稅費
        BigDecimal otherFeePrice = new BigDecimal(0);
        //預定服務費
        BigDecimal serviceFee = new BigDecimal(0);

        //获取核对订单信息
        List<ConditionDTO> conditionReqList = Lists.newArrayListWithExpectedSize(5);
        ShipReservationOrderReq shipReservationOrderReq = new ShipReservationOrderReq();
        ConditionDTO conditionDTO = new ConditionDTO();
        conditionDTO.setId(productId);
        conditionDTO.setQueryDate(startDate);
        conditionReqList.add(conditionDTO);
        shipReservationOrderReq.setConditionReqList(conditionReqList);
        ShipPriceRemainderDTO shipSalePriceInfoHandle = iAppShipProductService.findShipSalePriceInfoHandle(3, Long.valueOf(productId), LocalDate.now(), channelId);
        if(shipSalePriceInfoHandle == null){
            throw new BusinessException(SystemError.SHIP_PRODUCT_11051);
        }
        //加辐费
        List<PeoplesPriceDto> peoplesPrices = iAppShipProductService.getPeoplesPrices(Long.valueOf(productId), startDate);
        if(CollectionUtil.isNotEmpty(peoplesPrices)){
            for(PeoplesPriceDto priceDto : peoplesPrices){
                //成人
                if(priceDto.getTouristTypeId() == 1L){
                    adultPrice = shipSalePriceInfoHandle.getPrice().add(shipSalePriceInfoHandle.getReserveCharge()).add(shipSalePriceInfoHandle.getTax());
                    beforeAdultPrice = shipSalePriceInfoHandle.getPrice();
                }
                //小童
                if(priceDto.getTouristTypeId() == 2L){
                    childPrice = shipSalePriceInfoHandle.getPrice().add(shipSalePriceInfoHandle.getReserveCharge()).add(shipSalePriceInfoHandle.getTax());
                    beforeChildPrice = shipSalePriceInfoHandle.getPrice();
                }
            }
            otherFeePrice = shipSalePriceInfoHandle.getTax();
        }

        /**保存旅客信息 以及计算旅客成本*/
        saveTouristInfo(user, touristMap, shipOrderAmountItem, adultTotalNumber, childrenTotalNumber, orderId, shipOrderTouristList, touristSwitch, map, adultPrice, childPrice, beforeAdultPrice, beforeChildPrice, otherFeePrice);
        priceMap.put(Long.valueOf(productId),map);
        return shipReserveDTO;
    }

    /**
     * 保存旅客信息
     * @param user
     * @param touristMap
     * @param shipOrderAmountItem
     * @param adultTotalNumber
     * @param childrenTotalNumber
     * @param orderId
     * @param shipOrderTouristList
     * @param touristSwitch
     * @param map
     * @param adultPrice
     * @param childPrice
     * @param beforeAdultPrice
     * @param beforeChildPrice
     * @param otherFeePrice
     */
    private void saveTouristInfo(TokenUser user, Map<Long, ShipOrderTourist> touristMap, AppShipOrderAmountItem shipOrderAmountItem, AtomicInteger adultTotalNumber, AtomicInteger childrenTotalNumber, Long orderId, List<ShipOrderTouristReq> shipOrderTouristList, boolean touristSwitch, Map<Integer, BigDecimal> map, BigDecimal adultPrice, BigDecimal childPrice, BigDecimal beforeAdultPrice, BigDecimal beforeChildPrice, BigDecimal otherFeePrice) {
        for (ShipOrderTouristReq shipOrderTouristReq : shipOrderTouristList) {
            ShipOrderTourist shipOrderTourist = new ShipOrderTourist();
            long touristId = SnowflakeIdWorker.nextId();
            BeanUtils.copyProperties(shipOrderTouristReq, shipOrderTourist);
            shipOrderTourist.setId(touristId);
            shipOrderTourist.setOrderId(orderId);
            shipOrderTourist.setGmtCreate(LocalDateTime.now());
//            shipOrderTourist.setCreateId(user.getId());

            //成人
            if(shipOrderTouristReq.getTouristTypeId() == 1){
                //成本價+加幅費
                shipOrderAmountItem.setAdultAmount(shipOrderAmountItem.getAdultAmount().add(beforeAdultPrice));
                //订单总额=成人價格+小童價格+...
                shipOrderAmountItem.setTotalAmount(shipOrderAmountItem.getTotalAmount().add(adultPrice));
                map.put(shipOrderTouristReq.getTouristTypeId(),beforeAdultPrice);
                adultTotalNumber.incrementAndGet();
            }
            //小童
            else if(shipOrderTouristReq.getTouristTypeId() == 2){
                //成本價+加幅費
                shipOrderAmountItem.setChildrenAmount(shipOrderAmountItem.getChildrenAmount().add(beforeChildPrice));
                //订单总额=成人價格+小童價格+...
                shipOrderAmountItem.setTotalAmount(shipOrderAmountItem.getTotalAmount().add(childPrice));
                map.put(shipOrderTouristReq.getTouristTypeId(),beforeChildPrice);
                childrenTotalNumber.incrementAndGet();
            }
            //長者 暫時不支持
//            else if(shipOrderTouristReq.getTouristTypeId() == 3){
//                shipOrderAmountItem.setOldAmount(shipOrderAmountItem.getOldAmount().add(oldPrice).add(serviceFee));
//            }
            //稅費
            shipOrderAmountItem.setChildrenTaxAmount(otherFeePrice);
            shipOrderAmountItem.setAdultTaxAmount(otherFeePrice);

            if (touristSwitch) {
                shipOrderTouristMapper.insert(shipOrderTourist);
                touristMap.put(Long.valueOf(shipOrderTouristReq.getTouristType()),shipOrderTourist);
            }
        }
    }
}
